<template>
  <div class="app-container app-container-feedback">
    <div class="wrapper wrapper-content animated fadeInRight">
      <el-row>
        <el-col>
          <div class="ibox chat-view">
            <div class="ibox-title">聊天窗口</div>
            <div class="ibox-content">
              <el-row>
                <el-col :xs="18" :sm="18">
                  <div class="chat-discussion" v-loading="loading">
                    <div
                      class="chat-message"
                      :class="{
                        userChatMeClas: userName == chatItem.fromUser.username,
                      }"
                      v-for="(chatItem, index) in chatMessageList"
                      :key="index"
                    >
                      <img
                        class="message-avatar"
                        :src="domainBase + chatItem.fromUser.avatar"
                        alt=""
                      />
                      <div class="message refMessage">
                        <a class="message-author" href="#">
                          {{ chatItem.fromUser.username }}</a
                        >
                        <span class="message-date">
                          {{ chatItem.createTime }}
                        </span>
                        <div v-if="chatItem.type == 'text'">
                          <span class="message-content">{{
                            chatItem.content
                          }}</span>
                        </div>
                        <div
                          v-if="chatItem.type == 'image'"
                          class="messageContentImage"
                        >
                          <img
                            class="message-content"
                            :src="domainBase + chatItem.content"
                          />
                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="chat-message-form" v-if="fromUserName">
                    <div class="form-group">
                      <el-upload
                        action="#"
                        :http-request="requestUpload"
                        :show-file-list="false"
                        title="选择图片"
                        :before-upload="beforeUpload"
                      >
                        <svg-icon
                          icon-class="tu_pian"
                          class-name="card-panel-icon"
                        />
                      </el-upload>
                      <textarea
                        @keydown="messageSendlisten"
                        class="form-control message-input"
                        name="message"
                        maxlength="300"
                        v-model.trim="user_input"
                        placeholder="输入消息内容，按回车键发送"
                      ></textarea>
                    </div>
                  </div>
                </el-col>
                <el-col :xs="6" :sm="6">
                  <div class="chat-users">
                    <div class="users-list">
                      <div
                        class="chat-user"
                        :class="{
                          activeClas:
                            fromUserName == chatItem.fromUser.username,
                        }"
                        @click="showSessionDetail(chatItem)"
                        v-for="(chatItem, index) in allChatArr"
                        :key="index"
                      >
                        <img
                          class="chat-avatar"
                          :src="domainBase + chatItem.fromUser.avatar"
                          alt=""
                        />
                        <div
                          class="chat-user-name"
                          v-if="chatItem.unReadCount > 0"
                        >
                          <el-badge :value="chatItem.unReadCount" :max="99">
                            <a href="#">{{ chatItem.fromUser.username }}</a>
                          </el-badge>
                        </div>
                        <div
                          class="chat-user-name"
                          v-if="chatItem.unReadCount == 0"
                        >
                          <a href="#">{{ chatItem.fromUser.username }}</a>
                        </div>
                      </div>
                    </div>
                  </div>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { getAllChat, getAllChatFromUser, sendTextMsg, sendImageMsg, getNewMessage, clearUnreadMsgCount } from "@/api/biz";
import store from "@/store";

export default {
  name: "feedback",
  data () {
    return {
      domainBase: process.env.VUE_APP_BASE_API,
      allChatArr: [],
      chatMessageList: [],
      user_input: '',
      fromUserName: '',//点击当前用户
      loading: false,
      newMessageTimer: null,
      initTimer: null
    };
  },
  computed: {
    userName () {
      return this.$store.state.user.name
    }
  },
  created () {
    this.getList();
    // this.clearUnreadMsgCount();   //清除未读消息
    this.scrollToBottom()
  },
  mounted () {
    this.initTimer = setInterval(() => {
      this.getList();
      //滚动条始终保持在低端
      // this.scrollToBottom()
    }, 1000)
    // this.$once('hook:beforeDestroy', ()=>{
    //   clearInterval(this.initTimer)
    //   if (this.newMessageTimer){
    //     clearInterval(this.newMessageTimer)
    //   }
    // })
  },
  methods: {
    // 上传预处理
    beforeUpload (file) {
      if (file.type.indexOf("image/") == -1) {
        this.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
      }
    },
    // 上传行为
    requestUpload (data) {
      let formData = new FormData();
      formData.append("toUser", this.fromUserName);
      formData.append("image", data.file)
      sendImageMsg(formData).then(response => {
        if (response.code == 200) {
          this.chatMessageList = this.chatMessageList.concat(response);
          this.scrollToBottom()
        } else {
          this.$message.error("发送图片失败");
        }
      });
    },
    /** 聊天窗口滚动条在底部 */
    scrollToBottom () {
      this.$nextTick(() => {
        let container = this.$el.querySelector(".chat-discussion");
        container.scrollTop = container.scrollHeight;
      })
    },
    /** 查询所有回话列表 */
    getList () {
      getAllChat().then(
        response => {
          this.allChatArr = response
        }
      );
    },
    /** 获取单个聊天记录*/
    showSessionDetail (item) {
      this.fromUserName = item.fromUser.username
      this.getAllChatFromUser(this.fromUserName)
      if (this.newMessageTimer != null) {    //清除上一个定时器
        clearInterval(this.newMessageTimer)
      }
      this.newMessageTimer = setInterval(() => {
        this.getNewMessage(this.fromUserName);
      }, 1000)
    },
    /** 获取单个会话的新消息 */
    getNewMessage (fromUserName) {
      getNewMessage(fromUserName).then(response => {
        if (response && response.length > 0) {
          this.chatMessageList = this.chatMessageList.concat(response);
          this.scrollToBottom()
        }
      });
    },
    getAllChatFromUser (fromUserName) {
      this.loading = true
      getAllChatFromUser(fromUserName).then(response => {
        this.loading = false
        this.chatMessageList = response;
        this.scrollToBottom()
      });
    },
    /** 发送消息*/
    messageSendlisten (event) {
      if (event.keyCode === 13) {
        this.messageSend(); // 发送文本
        event.preventDefault(); // 阻止浏览器默认换行操作
        return false;
      }
    },
    messageSend () {
      let form = {
        text: this.user_input,
        toUser: this.fromUserName
      }
      sendTextMsg(form).then(response => {
        if (response.code == 200) {
          this.user_input = ''
          this.chatMessageList = this.chatMessageList.concat(response);
          this.scrollToBottom()
        } else {
          this.$message.error("发送消息失败");
        }
      });
    }
  },
  // destroyed() {
  //   if (this.newMessageTimer!=null){
  //     clearInterval(this.newMessageTimer);
  //     this.newMessageTimer=null
  //   }
  //   clearInterval(this.initTimer)
  //   this.initTimer = null
  // },
  //在 beforeRouteLeave (to, from, next) {} 离开路由的时候清除定时器
  beforeRouteLeave (to, from, next) {
    if (this.newMessageTimer != null) {
      clearInterval(this.newMessageTimer);
    }
    clearInterval(this.initTimer)
    next()
  }
};
</script>
<style  lang="scss">
.app-container-feedback {
  .messageContentImage {
    width: 100%;
    background: #f2f2f2;
    display: flex;
    justify-content: center;
    align-items: center;
    img {
      max-width: 100%;
      max-height: 100%;
    }
  }
  .card-panel-icon {
    font-size: 20px;
    padding: 2px;
  }
  .wrapper {
    padding: 0 20px;
  }
  .wrapper-content {
    padding: 20px;
  }
  .wrapper .middle-box {
    margin-top: 140px;
  }
  .animated.modal.fade .modal-dialog {
    -webkit-transform: none;
    -ms-transform: none;
    transform: none;
  }
  .ibox-content h1,
  .ibox-content h2,
  .ibox-content h3,
  .ibox-content h4,
  .ibox-content h5,
  .ibox-title h1,
  .ibox-title h2,
  .ibox-title h3,
  .ibox-title h4,
  .ibox-title h5 {
    margin-top: 5px;
  }
  .ibox-content.text-box {
    padding-bottom: 0;
    padding-top: 15px;
  }
  .ibox {
    clear: both;
    margin-bottom: 25px;
    margin-top: 0;
    padding: 0;
  }
  .ibox.collapsed .ibox-content {
    display: none;
  }
  .ibox.collapsed .fa.fa-chevron-up:before {
    content: "\f078";
  }
  .ibox.collapsed .fa.fa-chevron-down:before {
    content: "\f077";
  }
  .ibox:after,
  .ibox:before {
    display: table;
  }
  .ibox-title {
    -moz-border-bottom-colors: none;
    -moz-border-left-colors: none;
    -moz-border-right-colors: none;
    -moz-border-top-colors: none;
    background-color: #fff;
    border-color: #e7eaec;
    -webkit-border-image: none;
    -o-border-image: none;
    border-image: none;
    border-style: solid solid none;
    border-width: 2px 0 0;
    color: inherit;
    margin-bottom: 0;
    padding: 14px 15px 7px;
    min-height: 48px;
  }
  .ibox-content {
    color: inherit;
    border-color: #e7eaec;
    -webkit-border-image: none;
    -o-border-image: none;
    border-image: none;
    border-style: solid solid none;
    border-width: 1px 0;
  }
  .ibox-content {
    clear: both;
  }
  .ibox-heading {
    background-color: #f3f6fb;
    border-bottom: none;
  }
  .ibox-heading h3 {
    font-weight: 200;
    font-size: 24px;
  }
  .ibox-title h5 {
    display: inline-block;
    font-size: 14px;
    margin: 0 0 7px;
    padding: 0;
    text-overflow: ellipsis;
    float: left;
  }
  .ibox-title .label {
    float: left;
    margin-left: 4px;
  }
  .ibox-tools {
    display: inline-block;
    float: right;
    margin-top: 0;
    position: relative;
    padding: 0;
  }
  .ibox-tools a {
    cursor: pointer;
    margin-left: 5px;
    color: #c4c4c4;
  }
  .ibox-tools a.btn-primary {
    color: #fff;
  }
  .ibox-tools .dropdown-menu > li > a {
    padding: 4px 10px;
    font-size: 12px;
  }
  .ibox .open > .dropdown-menu {
    left: auto;
    right: 0;
  }
  .chat-view {
    border: 1px solid #f3f3f4;
    z-index: 20012;
    font-size: 13px;
    line-height: 1.42;
    color: #676a6c;
  }
  .text-muted {
    color: #888;
  }
  .message-avatar {
    height: 48px;
    width: 48px;
    border: 1px solid #e7eaec;
    border-radius: 4px;
    margin-top: 1px;
  }
  .chat-discussion .chat-message .message-avatar {
    float: left;
    margin-right: 10px;
  }
  .chat-discussion .userChatMeClas .message-avatar {
    float: right;
    margin-left: 10px;
  }
  .chat-discussion .chat-message .message-date {
    float: right;
  }
  .chat-discussion .userChatMeClas .message-date {
    float: left;
  }
  .chat-discussion .chat-message .message {
    text-align: left;
    margin-left: 55px;
  }
  .chat-discussion .userChatMeClas .message {
    text-align: right;
    margin-right: 55px;
  }
  .message {
    background-color: #fff;
    border: 1px solid #e7eaec;
    text-align: left;
    display: block;
    padding: 10px 20px;
    position: relative;
    border-radius: 4px;
  }
  .message-date {
    font-size: 10px;
    color: #888;
  }
  .message-content {
    display: block;
  }
  .chat-users {
    overflow-y: auto;
    height: 400px;
  }
  .chat-avatar {
    width: 36px;
    height: 36px;
    float: left;
    margin-right: 10px;
  }
  .chat-user-name {
    padding: 10px;
  }
  .chat-user {
    padding: 8px 10px;
    border-bottom: 1px solid #e7eaec;
  }
  .chat-user a {
    color: inherit;
  }
  .chat-message-form .form-group {
    margin-bottom: 0;
    border: 1px solid #e5e6e7;
  }
  .chat-message {
    padding: 10px 20px;
  }
  .chat-discussion {
    background: #eee;
    padding: 15px;
    height: 400px;
    overflow-y: auto;
  }
  a.message-author {
    color: #337ab7;
    text-decoration: none;
  }

  element.style {
  }
  .badge-primary,
  .label-primary {
    background-color: #1ab394;
    color: #fff;
  }
  .label {
    background-color: #d1dade;
    color: #5e5e5e;
    font-size: 10px;
    font-weight: 600;
    padding: 3px 8px;
    text-shadow: none;
  }
  .pull-right {
    float: right !important;
  }
  .label-primary {
    background-color: #337ab7;
  }
  .label {
    display: inline;
    padding: 0.2em 0.6em 0.3em;
    font-size: 75%;
    font-weight: 700;
    line-height: 1;
    color: #fff;
    text-align: center;
    white-space: nowrap;
    vertical-align: baseline;
    border-radius: 0.25em;
  }
  .label {
    background-color: #d1dade;
    color: #5e5e5e;
    font-size: 10px;
    font-weight: 600;
    padding: 3px 8px;
    text-shadow: none;
  }
  .badge-primary,
  .label-primary {
    background-color: #1ab394;
    color: #fff;
  }
  .form-control,
  .single-line {
    background-color: #fff;
    background-image: none;
    border-radius: 1px;
    color: inherit;
    display: block;
    padding: 6px 12px;
    -webkit-transition: border-color 0.15s ease-in-out 0s,
      box-shadow 0.15s ease-in-out 0s;
    transition: border-color 0.15s ease-in-out 0s,
      box-shadow 0.15s ease-in-out 0s;
    width: 100%;
    font-size: 14px;
  }
  .message-input {
    height: 90px !important;
    border: none;
  }
  .chat-user-name .el-badge__content.is-fixed {
    right: 0 !important;
  }
  .activeClas {
    background: #f2f2f2;
  }
  textarea:focus,
  input:focus {
    outline: none;
  }
}
</style>
